﻿using System.Linq;
using System;
using System.Collections.Generic;
using Citi.Import.Util;
using Citi.GocAttributes.Domain.Utils;

namespace Citi.GocAttributes.Domain
{
    public partial class Country
    {
        private const string ManagedGeographyIdColumnName = "C_DSMT_TN_MGEO";
        private const string ManagedGeographyColumnName = "MGEO_PN_DESCR254";
        
        public static readonly List<Definition<Country>> Definitions = new List<Definition<Country>>
            {
                new Definition<Country> { ModelProperty = x => x.Abbreviation, MaxLength = 5, Required = true, ColumnName = ManagedGeographyIdColumnName, CustomConversionMethod = ValidateAbbreviation},
                new Definition<Country> { ModelProperty = x => x.Description, MaxLength = 50, Required = true, ColumnName = ManagedGeographyColumnName},
            };

        private static object ValidateAbbreviation(ref Country model, string value, List<string> fields, ref string error, List<string> headers = null)
        {
            if (String.IsNullOrEmpty(value))
            {
                error = String.Format(ErrorFieldNull, ManagedGeographyIdColumnName);
                return Conversion.Validation.Failed;
            }

            var domain = CacheFacade.Get(SelectAll<Country>).FirstOrDefault(x => x.Abbreviation == value);

            if (domain != null)
            {
                model = domain;
                return Conversion.Validation.Validated;
            }

            return value;
        }
        
        public static void Save(IEnumerable<Country> countries)
        {
            var toSave = countries.Distinct(new CountryComparer()).Where(x => x != null && !String.IsNullOrEmpty(x.Abbreviation) && x.Id == 0).ToList();

            if (toSave.Any())
                toSave.First().Save(toSave, 100);

            CacheFacade.Clear(typeof(Country));
        }

        public Country SelectByAbbreviation(string abbreviation)
        {
            return SelectAll<Country>().FirstOrDefault(x => x.Abbreviation == abbreviation);
        }
    }

    public class CountryComparer : IEqualityComparer<Country>
    {
        public bool Equals(Country x, Country y)
        {
            if (ReferenceEquals(x, y)) return true;
            if (ReferenceEquals(x, null) || ReferenceEquals(y, null))
                return false;

            return x.Description == y.Description && x.Abbreviation == y.Abbreviation && x.Id == y.Id;
        }

        public int GetHashCode(Country item)
        {
            if (ReferenceEquals(item, null)) return 0;

            var hashDescription = item.Description == null ? 0 : item.Description.GetHashCode();
            var hashId = item.Description == null ? 0 : item.Id.GetHashCode();

            return hashDescription ^ hashId;
        }
    }
}
